package com.tbit.uqbike.webmanager.controller;

import com.tbit.uqbike.annos.OperateLog;
import com.tbit.uqbike.constant.UserConstant;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.Adaccount;
import com.tbit.uqbike.object.pojo.AdvertConfig;
import com.tbit.uqbike.object.pojo.Image;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.uqbike.service.business.AdaccountService;
import com.tbit.uqbike.service.business.ImageService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

/**
 * @author chenmengran
 * @Description: 广告控制
 * @date 2020\1\7 000714:10
 */
@Validated
@RestController
@Slf4j
@RequestMapping(value = "/advert", produces = BaseController.MEDIA_JSON_UTF8)
public class AdaccountController extends BaseController {
    @Autowired
    private AdaccountService adaccountService;
    @Autowired
    private ImageService imageService;

    @RequestMapping("/getAdvert")
    public JsonResult getAdvert(Integer accountId, Integer type, String sortName,
                                @RequestParam(defaultValue = "1") Integer sign,
                                @RequestParam(defaultValue = "10") Integer rowCount,
                                @RequestParam(defaultValue = "1") Integer pageNO,
                                HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        if (loginInfo.type.equals(UserConstant.USER_AGENT)) {
            accountId = loginInfo.id;
        } else {
            Assert.notNull(accountId, "ver.accountId.notNull");
        }
        if (sortName != null && !"".equals(sortName)) {
            sortName = sortName + (sign == 1 ? " asc" : " desc");
        }
        List<Adaccount> adaccountList = adaccountService.queryPage(accountId, type, sortName, rowCount, pageNO);
        //查询总数
        Integer total = adaccountService.getTotal(accountId, type);
        return JsonResult.ok(adaccountList, total);
    }

    /**
     * 添加广告
     *
     * @param accountId
     * @param type
     * @param file
     * @param title
     * @param openURL
     * @param remark
     * @param startTime
     * @param endTime
     * @param request
     * @return
     */
    @RequestMapping("addAdvert")
    @OperateLog(module = ModuleEnum.ADVERT, methods = MethodEnum.ADD_ADVERT)
    public JsonResult addAdvert(Integer accountId, MultipartFile[] file, String remark,
                                @NotNull(message = "ver.type.notNull") Integer type,
                                @NotNull(message = "ver.title.notNull") String title, String openURL,
                                @NotNull(message = "ver.startTime.notNull") Long startTime,
                                @NotNull(message = "ver.endTime.notNull") Long endTime,
                                HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        if (loginInfo.type.equals(UserConstant.USER_AGENT)) {
            accountId = loginInfo.id;
        } else {
            Assert.notNull(accountId, "ver.accountId.notNull");
        }
        adaccountService.addAdvert(accountId, file, type, title, openURL, remark, startTime, endTime);
        return JsonResult.ok();
    }

    /**
     * 更新广告
     *
     * @param accountId 区域id
     * @param file      图片文件
     * @param remark    备注
     * @param adId      广告id
     * @param url       图片url(不传文件就用这个)
     * @param type      类型
     * @param title     标题
     * @param openURL   url
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param request
     * @return
     */
    @RequestMapping("updateAdvert")
    @OperateLog(module = ModuleEnum.ADVERT, methods = MethodEnum.ADD_ADVERT)
    public JsonResult updateAdvert(Integer accountId, MultipartFile[] file, String remark,
                                   @NotNull Integer adId,
                                   String url,
                                   @NotNull(message = "ver.type.notNull") Integer type,
                                   @NotNull(message = "ver.title.notNull") String title, String openURL,
                                   @NotNull(message = "ver.startTime.notNull") Long startTime,
                                   @NotNull(message = "ver.endTime.notNull") Long endTime,
                                   HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        Assert.notNull(adId, "广告id不能为空");
        if (loginInfo.type.equals(UserConstant.USER_AGENT)) {
            accountId = loginInfo.id;
        } else {
            Assert.notNull(accountId, "ver.accountId.notNull");
        }
        adaccountService.updateAdvert(accountId, file, type, title, openURL, remark, startTime, endTime, url, loginInfo, adId);
        return JsonResult.ok();
    }

    /**
     * 删除广告
     *
     * @param adId
     * @param request
     * @return
     */
    @RequestMapping("delAdvert")
    @OperateLog(module = ModuleEnum.ADVERT, methods = MethodEnum.DEL_ADVERT)
    public JsonResult delAdvert(@NotNull(message = "ver.adId.notNull") Integer adId, HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        adaccountService.delAdvert(loginInfo, adId);
        return JsonResult.ok();
    }

    /**
     * 获取图片信息
     *
     * @param imageId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("getImage")
    public void getImage(@NotNull(message = "ver.imageId.notNull") String imageId, HttpServletRequest request, HttpServletResponse response) {
        LoginInfo loginInfo = getLogin(request);
        Image image = imageService.getByImageId(imageId);
        if (image == null) {
            throw new BaseException(SystemCodeEnum.IMAGE_NOT_EXIT);
        }
        try {
            if (image.getImageContent().length > 0) {
                OutputStream out = response.getOutputStream();
                try {
                    out.write(image.getImageContent());
                    out.flush();
                } catch (Exception e) {
                    e.getMessage();
                } finally {
                    out.close();
                }
            }
        } catch (Exception e) {
            LogUtil.warn("图片读取失败： " + e.getMessage());
            throw new BaseException(SystemCodeEnum.READ_IMAGE_FAILE);
        }

    }

    /**
     * @param adId
     * @param sort
     * @param openURL
     * @return com.tbit.uqbike.object.view.JsonResult
     * @Description: 图片自定义顺序
     * @createDate 2020/12/28 11:31
     */
    @PostMapping("/update")
    public JsonResult update(@NotNull(message = "ver.adId.notNull") Integer adId,
                             @NotNull(message = "ver.sort.notNull") @Max(value = 100, message = "请输入小于100的数字") Integer sort,
                             String openURL) {
        adaccountService.update(new HashMap<>(), adId, sort, openURL);
        return JsonResult.ok();
    }


    /**
     * 修改广告配置
     *
     * @param
     * @return
     */
    @PostMapping("/editAdvertConfig")
    @OperateLog(module = ModuleEnum.ADVERTCONFIG, methods = MethodEnum.ADVERTCONFIG_UPDATE)
    public JsonResult editAdvertConfig(AdvertConfig advertConfig, HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        if (loginInfo.type.equals(UserConstant.USER_AGENT)) {
            advertConfig.setAccountId(loginInfo.id);
        } else {
            Assert.notNull(advertConfig.getAccountId(), "ver.accountId.notNull");
        }
        adaccountService.editAdvertConfig(advertConfig);
        //更新区域广告id（跟随品牌来）
        adaccountService.updateAdAccountIdFlowNo();
        return JsonResult.ok();
    }

    /**
     * 获取广告配置
     *
     * @param
     * @return
     */
    @PostMapping("/getAdvertConfig")
    public JsonResult getAdvertConfig(AdvertConfig advertConfig, HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);

        if (loginInfo.type.equals(UserConstant.USER_AGENT)) {
            advertConfig.setAccountId(loginInfo.id);
        } else {
            Assert.notNull(advertConfig.getAccountId(), "ver.accountId.notNull");
        }

        List<AdvertConfig> advertConfigList = adaccountService.getAdvertConfig(advertConfig);

//        /**设置默认值，全部默认设置未开启*/
//        if (advertConfig==null){
//            advertConfig=new AdvertConfig();
//            advertConfig.setAccountId(advertConfig.getAccountId());
//            advertConfig.setAdvertPosition(0);
//            advertConfig.setAdvertSwitch(0);
//            advertConfig.setAdvertType(0);
//        }

        return JsonResult.ok(advertConfigList);
    }

    /**
     * 添加流量主id
     *
     * @param
     * @return
     */
    @PostMapping("/addFlowNo")
    @OperateLog(module = ModuleEnum.ADVERT, methods = MethodEnum.ADD_TRAFFIC)
    public JsonResult addFlowNo(AdvertConfig advertConfig) {
        if (null == advertConfig.getAdvertNo()) {
            throw new BaseException(SystemCodeEnum.SYSTEM_ERROR);
        }
        if (advertConfig.getAdvertNo().length() > 50){
            throw new BaseException("广告id过长");
        }
        Integer count = adaccountService.addAdvertNo(advertConfig);
        if (count <= 0) {
            throw new BaseException(SystemCodeEnum.ADVERT_CONFIG_NOT_EXIST);
        }
        //更新区域广告id（跟随品牌来）
        adaccountService.updateAdAccountIdFlowNo();
        return JsonResult.ok();
    }


}
